<?php
namespace app\model;

/**
 * Author: cbw
 * Desc: 客资收集表单
 * Time: 2022/4/13 10:18
 * Email: 17854288794@163.com
 */


class Otherform{
    /**
     * Desc:格式化返回前端多表单数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/4/14 10:42
     * @param $themeid
     * @return array
     */
    public static function formatConfig($themeid,$mode=1)
    {
        $format_res =[];
        $config = Theme::getConfig($themeid);
        if ($config['cusForm']){
            foreach ($config['cusForm'] as $k => $v){
                if ($mode==1){
                    $format_res[$k]['input_name'] = 'filed_'.$k;
                }elseif ($mode==2){
                    array_push($format_res,['name'=>$v['name'],'key'=>'filed_'.$k,'mode'=>$v['mode']]);
                }elseif ($mode==3){
                    array_push($format_res,['name'=>$v['name'],'input_name'=>'filed_'.$k,'mode'=>$v['mode'],'vals'=>$v['vals'],
                        'vals_min'=>$v['vals_min'],'vals_max'=>$v['vals_max']]);
                }
            }
        }else{
            array_push($format_res,['name'=>'姓名','input_name'=>'filed_0','mode'=>8,'vals'=>'','key'=>'filed_0',
                'vals_min'=>0,'vals_max'=>0]);
            array_push($format_res,['name'=>'电话','input_name'=>'filed_1','mode'=>6,'vals'=>'','key'=>'filed_1',
                'vals_min'=>0,'vals_max'=>0]);
            if ($mode==2){
                $item = Otherform::getItem(['id >'=>0]);
                $fileds_arr = json_decode($item['fileds'],true);
                if ($fileds_arr){
                    $jk = 3;
                    foreach ($fileds_arr as $k => $v){
                        if (!in_array($k,['filed_0','filed_1'])){
                            array_push($format_res,['name'=>'字段'.$jk,'key'=>$k,'mode'=>0]);
                            $jk+=1;
                        }
                    }
                }
            }
        }

        return $format_res;
    }

    public static function addItem($data)
    {
        $data['created_at']=date("Y-m-d H:i:s",time());
        $res = $insertid = db_insert(t_fans_other_form,$data);
        return $res;
    }

    public static function editItem($data,$where)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = db_update(t_fans_other_form,$data,$where);
        return $res;
    }

    public static function getItem($where)
    {
        $res = db_get(t_fans_other_form,$where);
        return $res;
    }

    public static function validateFileds($themeid,$params)
    {
        $config_fileds = self::formatConfig($themeid);
        foreach ($config_fileds as $k => $v){
            $validate_filed_name = $v['input_name'];
            $validate_pre_msg = $v['name'];
            if (!$params[$validate_filed_name] || !isset($params[$validate_filed_name])){
                //字段不存在
                return $validate_pre_msg.'不能为空';
            }
        }
        return true;
    }

    public static function formatInputData1($data,$themeid,$get_userinfo = false)
    {
        $format_res =[];
        $config = Theme::getConfig($themeid);
        $user_info = [];
        if (!empty($config['cusForm'])){
            foreach ($config['cusForm'] as $k => $v){
                $temp_key = 'filed_'.$k;
                if (is_array($data[$temp_key])){
                    $format_res[$temp_key] = implode("|",$data[$temp_key]);
                }else{
                    $format_res[$temp_key] = $data[$temp_key];
                    if ($v['mode']==8){
                        $user_info['username'] = $data[$temp_key];
                    }
                    if ($v['mode']==6){
                        $user_info['mobile'] = $data[$temp_key];
                    }
                }
            }
        }
        if ($get_userinfo){
            return $user_info;
        }
        return json_encode($format_res);
    }

    public static function submitCusInfo($system,$themeid,$fans,$workerid,$fileds)
    {
        global $_P, $_G;
        $config = Theme::getConfig($themeid);
        if ($_P['friendhelp']==1) {
            $uid = $_P['fromuid'];
            $result = Share::friendhelp($system,$config, $themeid, $fans, $uid);
            if ($result['errcode']!=1){
                $res = array(
                    'error' => $result['errcode']-1,
                    'msg' => $result['msg'],
                    'data' => $result
                );
                return $res;
            }
        }

        $new_temp_arr= [
            'themeid'=>$themeid,
            'uid'=>$fans['uid'],
            'workerid'=>$workerid,
            'fileds'=> Otherform::formatInputData1($fileds,$themeid),
            'created_at'=>date("Y-m-d H:i:s",time())
        ];
        if (isset($_P['fromuid']) && $_P['fromuid']){
            $new_temp_arr['fromuid'] = $_P['fromuid'];
        }
        $user_info = Otherform::formatInputData1($fileds,$themeid,true);
        $item = Otherform::getItem(['uid'=>$fans['uid'],'themeid'=>$themeid]);
        if (!$item){
            $res = Otherform::addItem($new_temp_arr);
            if ($user_info && $user_info['username'] && $user_info['mobile']){
                $res1 = db_update(t_fans,$user_info,['uid'=>$fans['uid'],'themeid'=>$themeid]);
            }
        }else{
            unset($new_temp_arr['themeid']);
            unset($new_temp_arr['uid']);
            unset($new_temp_arr['created_at']);
            $res = Otherform::editItem($new_temp_arr,['themeid'=>$themeid,'uid'=>$fans['uid']]);
            if ($user_info && $user_info['username'] && $user_info['mobile']){
                $res1 = db_update(t_fans,$user_info,['uid'=>$fans['uid'],'themeid'=>$themeid]);
            }
        }

        if ($res){
            if ($_P['otherformjoin']==1){
                if ($config['friendorder']==1 && $config['isicon']==3 || $config['get_mystery_boxes']==2) { //邀请好友助力未报名
                    Fans::setClickOpenBox($_G['member']['uid'], $themeid);
                }
                if ($config['get_mystery_boxes']==2){
                    $check_has_order = db_get(t_record,['themeid'=>$themeid,'openid'=>$fans['openid'],'uid'=>$fans['uid'],'status'=>0,'type'=>0,'fee'=>0]);
                    if ($check_has_order){
                        $res = array(
                            'error' => 1,
                            'msg' => '已存在记录,请勿重复提交',
                        );
                        return $res;
                    }
                    //判断盲盒创建订单
                    $data = array(
                        'uniacid'  => $_G['mpid'],
                        'themeid'  => $themeid,
                        'openid'   => $fans['openid'],
                        'uid'	    => $fans['uid'],
                        'avatar'	    => $fans['avatar'],
                        'nickname' => $fans['nickname'],
                        'username' => $user_info['username'],
                        'mobile' => $user_info['mobile'],
                        'fromuid' => $_P['fromuid'],
                        'status' => 0,
                        'type' => 0,
                        'fee' => 0,
                        'workerid' => $_P['workerid'],
                        'uncode' => $themeid.'-'.TIMESTAMP.rand(1000,1000000),
                        'billcode' => getMillisecond(),
                        'addtime' => TIMESTAMP,
                    );
                    $record_add_res = $insertid = db_insert(t_record,$data);
                }
                $msg='报名成功';
            }
            if ($_P['friendhelp']==1) {
                $msg=$result['msg'];
            }
            $res = array(
                'error' => 0,
                'msg' => empty($msg)?"提交成功":$msg,
            );
            return $res;
        }else{
            $res = array(
                'error' => 1,
                'msg' => '保存失败',
            );
            return $res;
        }
    }

    public static function getFlagTypeCount($themeid)
    {
        $type_list = [
            ['title'=>'全部','status'=>''],
        ];
        $config = Theme::getConfig($themeid);
        if (empty($config['cusForm'])){
            return ;
        }
        foreach ($config['cusForm'] as $k => $v){
            if ($v['mode']==2 || $v['mode']==3){
                //下拉 单选
                foreach ($v['vals'] as $kk => $vv){
                    array_push($type_list,['title'=>$vv,'status'=>$vv]);
                }
            }elseif ($v['mode']==4){
                //多选
                foreach ($v['vals'] as $kk => $vv){
                    array_push($type_list,['title'=>$vv['name'],'status'=>$vv['name']]);
                }
            }
        }

        foreach ($type_list as $key =>$val){
            $status = $val['status'];
            if (!$status){
                $sql = "select count(*) as cnt from " . tablename(t_fans_other_form)." where  themeid=".$themeid;
            }else{
                $status = '%'.$status.'%';
                $sql = "select count(*) as cnt from " . tablename(t_fans_other_form)." where  themeid=".$themeid." and fileds like '".$status."'";
            }
            $type_list[$key]['total'] =  intval(db_find($sql)['cnt']);
        }
        return $type_list;
    }

    //判断是否报名或者拆盲盒
    public static function getFlagClickOpenBox($themeid,$config,$fromuid=0)
    {
        $type_list = [
            ['title'=>'全部','click_open_box'=>0],
            ['title'=>'是','click_open_box'=>1],
            ['title'=>'否','click_open_box'=>2],
        ];
        //盲盒逻辑 点亮星星
        if ($config['isicon']==3 || $config['get_mystery_boxes']>0){
            foreach ($type_list as $k => $v){
                $click_open_box = $v['click_open_box'];
                if (!$click_open_box){
                    $sql = "select COUNT(distinct a.uid) as cnt from   " . tablename(t_friend) . " AS  a " .
                        " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
                        " WHERE a.themeid= $themeid ";
                }else{
                    $next_str = '';
                    if ($click_open_box==2){
                        $click_open_box = 0;
                        $next_str = " or b.click_open_box is null ";
                    }
                    $sql = "select COUNT(distinct a.uid) as cnt from   " . tablename(t_friend) . " AS  a " .
                        " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
                        " WHERE a.themeid= $themeid and (b.click_open_box = '".$click_open_box."'".$next_str.")";
                }
                if ($fromuid){
                    $sql .= " and a.fromuid=$fromuid";
                }
                $type_list[$k]['total'] =  intval(db_find($sql)['cnt']);
            }
        }else{
            foreach ($type_list as $k => $v){
                $click_open_box = $v['click_open_box'];
                if (!$click_open_box){
                    $sql = "select count(*) as cnt from   " . tablename(t_fans_other_form) . " AS  a " .
                        " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
                        " WHERE a.themeid= $themeid ";
                }else{
                    $next_str = '';
                    if ($click_open_box==2){
                        $click_open_box = 0;
                        $next_str = " or b.click_open_box is null ";
                    }
                    $sql = "select count(*) as cnt from   " . tablename(t_fans_other_form) . " AS  a " .
                        " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
                        " WHERE a.themeid= $themeid and (b.click_open_box = '".$click_open_box."'".$next_str.")";
                }
                $type_list[$k]['total'] =  intval(db_find($sql)['cnt']);
            }
        }
        return $type_list;
    }

    public static function getOrderStatusArr($themeid,$config,$fromuid=0)
    {
        //盲盒逻辑 点亮星星
        if ($config['isicon']==3 || $config['get_mystery_boxes']>0){
            $order_sql = " select COUNT(distinct a.uid) as cnt from ".tablename(t_friend)." as a".
                " left join ".tablename(t_record)." as b on a.themeid=b.themeid and a.uid=b.uid ".
                " left join ".tablename(t_fans)." as c on a.uid=c.uid and a.themeid=c.themeid ".
                " where a.themeid='$themeid' ";
            if ($fromuid){
                $order_sql.= " and a.fromuid=$fromuid";
            }
            $has_pay_sql = $order_sql." and (b.status=1 or b.status=3)";
            $all_total = db_find($order_sql)['cnt'];
            $has_pay_total = db_find($has_pay_sql)['cnt'];
            return [
                ['title'=>'不限','pay_status'=>0,'total'=>$all_total],
                ['title'=>'未支付','pay_status'=>2,'total'=>$all_total-$has_pay_total],
                ['title'=>'已支付','pay_status'=>1,'total'=>$has_pay_total],
            ];
        }else{
            //单纯表单收集
            $prefix_sql = " select count(*) as cnt from ".tablename(t_fans_other_form)." as a".
                " left join ".tablename(t_record)." as b on a.themeid=b.themeid and a.uid=b.uid ".
                " left join ".tablename(t_fans)." as c on a.uid=c.uid and a.themeid=c.themeid ".
                " where a.themeid='$themeid' ";
            $has_pay_sql = $prefix_sql." and (b.status=1 or b.status=3) group by a.id";
            $total = db_find($prefix_sql)['cnt'];
            $has_pay_total = db_find($has_pay_sql)['cnt'];
            return [
                ['title'=>'不限','pay_status'=>0,'total'=>$total],
                ['title'=>'未支付','pay_status'=>2,'total'=>$total-$has_pay_total],
                ['title'=>'已支付','pay_status'=>1,'total'=>$has_pay_total],
            ];
        }
    }

    public static function newSearchFlag($config,$themeid,$from_themeid,$search, $page_start = 0, $page_size = 10, $start_day, $end_day,$pay_status=0,$count=false,$workerid = 0,$show_help_flag=0,$click_open_box=0,$isexport = false,$export_type=0)
    {
        global $_G,$_P,$_S,$_C;
        $condition = "";
        //盲盒逻辑 点亮星星
        if ($config['isicon']==3 || $config['get_mystery_boxes']>0){
            if ($search) {
                $tmp_str = str_replace('%','',$search);
                if (preg_match('/^[0-9]+$/',$tmp_str) && strlen($tmp_str)!=11){
                    $_P['fromuid'] = $tmp_str;
                }else{
                    $condition .= " AND (b.nickname LIKE '" . $search . "'" . " or b.mobile LIKE '" . $search . "' " . " or b.username LIKE '" . $search . "') ";
                }
            }
        }else{
            if ($search) {
                $condition .= " AND (b.nickname LIKE '" . $search . "'" . " or b.mobile LIKE '" . $search . "' " . " or b.username LIKE '" . $search . "' " . " or a.fileds LIKE '" . $search . "') ";
            }
        }
        if (isset($_P['uids']) && $_P['uids']){
            $condition .= " and a.uid in (".$_P['uids'].") ";
        }
        if (isset($_P['fromuid']) && $_P['fromuid'] && ($config['isicon']==3 || $config['get_mystery_boxes']>0) && $export_type!=2){
            $fromuid = $_P['fromuid'];
            $condition .= " and a.fromuid='$fromuid' ";
        }
        if ($start_day && $end_day) {
            if ($config['isicon']==3 || $config['get_mystery_boxes']>0){
                $condition .= "  and a.addtime between '" . strtotime($start_day) . "' and '" . strtotime($end_day) . "'";
            }else{
                $condition .= "  and a.created_at between '" . $start_day . "' and '" . $end_day . "'";
            }
        }
        if ($pay_status>0 && $pay_status==2){
            $condition .= " and (d.status is null or (d.status=0 or d.status=-1)) ";
        }elseif ($pay_status>0 && $pay_status==1){
            $condition .= " and (d.status=1 or d.status=3) ";
        }elseif($pay_status==0){
            $condition .= " and (d.status is null or (d.status=0 or d.status=-1) or (d.status=1 or d.status=3))  ";
        }
        if ($click_open_box){
            if ($click_open_box==1){
                $condition .= " and (b.click_open_box=1) ";
            }
            if ($click_open_box==2){
                $condition .= " and (b.click_open_box=0 or b.click_open_box is null) ";
            }
        }
        if ($workerid){
            $condition .= " and a.workerid='$workerid' ";
        }
        if ($config['isicon']==3 || $config['get_mystery_boxes']>0){
            if ($page_size && !$count){
                $condition .= ' group by a.uid ';
            }
            $condition .= " ORDER BY a.addtime DESC ";
        }else{
            if ($page_size && !$count){
                $condition .= ' group by a.uid ';
            }
            $condition .= "  ORDER BY a.created_at DESC ";
        }
        if ($page_size && !$count) {
            $condition .= "LIMIT " . $page_start . "," . $page_size;
        }
        if ($config['isicon']==3 || $config['get_mystery_boxes']>0){
            $sql = " FROM " . tablename(t_friend) . " AS  a " .
                " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
                " LEFT JOIN " . tablename(t_fans) . " AS c on a.fromuid=c.uid and c.themeid = " . $from_themeid .
                " LEFT JOIN (SELECT * FROM ".tablename(t_record)." r1 WHERE id = (SELECT MAX(id) FROM ".tablename(t_record)." r2 WHERE r1.uid =  r2.uid AND r1.themeid = r2.themeid))  d on a.uid=d.uid and a.themeid = d.themeid " .
                " WHERE a.themeid=$themeid" . $condition;
        }else{
            $sql = " FROM " . tablename(t_fans_other_form) . " AS  a " .
                " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
                " LEFT JOIN " . tablename(t_fans) . " AS c on a.fromuid=c.uid and c.themeid = " . $from_themeid .
                " LEFT JOIN (SELECT * FROM ".tablename(t_record)." r1 WHERE id = (SELECT MAX(id) FROM ".tablename(t_record)." r2 WHERE r1.uid =  r2.uid AND r1.themeid = r2.themeid))  d on a.uid=d.uid and a.themeid = d.themeid " .
                " WHERE a.themeid=$themeid" . $condition;
        }
        if ($count){
            return  intval(db_fetchcolumn ( ' select COUNT(distinct a.uid)'.$sql));
        }else{
            if ($config['yukuan'] > 0 && TIMESTAMP > $config['yukuantime']) {
                $userlist = Fans::getWeiBukuanList($config,$themeid);
            }
            if ($config['isicon']==3 || $config['get_mystery_boxes']>0){
                $sql = " SELECT a.id,a.uid,a.fromuid,a.addtime,b.click_open_box,b.nickname,b.avatar,b.username,b.mobile,b.workerid as f_workerid,c.uid as fuid,c.avatar as favatar,c.nickname as fnickname,d.address as record_address " . $sql;
            }else{
                $sql = " SELECT a.*,b.avatar,b.nickname,b.click_open_box,b.username,b.mobile,b.workerid as f_workerid,c.uid as fuid,c.avatar as favatar,c.nickname as fnickname,d.address as record_address " . $sql;
            }
            $list =  db_select($sql);
            foreach($list as $k => $val){
                if ($config['isicon']==3 || $config['get_mystery_boxes']>0){
                    $has_fans_other_info = db_get(t_fans_other_form,['themeid'=>$themeid,'uid'=>$val['uid']],['fileds']);
                    if ($has_fans_other_info){
                        $val['fileds'] = $has_fans_other_info['fileds'];
                    }
                    $list[$k]['created_at'] = date("Y-m-d H:i:s",$val['addtime']);
                }
                if (isset($val['fileds'])){
                    $temp_fileds = json_decode($val['fileds'],true);
                    if ($temp_fileds){
                        foreach ($temp_fileds as $kk => $vv){
                            $list[$k][$kk] = $vv;
                        }
                    }
                }
                if (isset($val['workerid']) && $val['workerid']){
                    $workerid = $val['workerid'];
                }else{
                    $workerid = $val['f_workerid'];
                }
                $r = Worker::getWokerName($_S,$themeid,$workerid);
                $list[$k]['workername']=$r['workername'];
                $list[$k]['teamname']=$r['teamname'];
                $list[$k]['companyname']=$r['companyname'];

                $list[$k]['workername'] = $r['workername'];
                if (empty($list[$k]['workername'])){
                    $list[$k]['workername'] = '';
                    $list[$k]['teamname']='';
                    $list[$k]['companyname']='';
                }
                $themyrecord = Record::getAllthemeIspay($val['uid']);
                $list[$k]['pay_status'] = getPayStatus($config,$themeid,$userlist,$themyrecord['id'],$themyrecord['status'],$themyrecord['addtime'],$themyrecord['type'],$isexport);
                if ($show_help_flag){
                    //判断给谁助力
                    if (!isset($_P['fromuid'])){
                        $list[$k]['friend_list'] = self::getHelpUserInfoList($themeid,$val['uid']);
                    }else{
                        $list[$k]['friend_list'] = self::getHelpUserInfoList($themeid,$val['uid'],$_P['fromuid']);
                    }
                }
            }
            return $list;
        }
    }


    /**
     * Desc:获取助力人信息集合
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/10/29 15:25
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getHelpUserInfoList($themeid,$uid,$fromuid=0)
    {
        if ($fromuid){
            $sql = " select uid,username,mobile from ".tablename(t_fans)." where themeid='$themeid' and uid='$fromuid'";
            $res =db_find($sql);
            if (!$res){
                return;
            }
            $list = [];
            $list[] = $res;
            return $list;
        }
        //获取当前用户的助力记录
        $friend_flag = db_getall(t_friend,['themeid'=>$themeid,'uid'=>$uid]);
        if (empty($friend_flag)){
            return;
        }
        //格式化当前被助力人的uids
        $search_uids = '';
        foreach ($friend_flag as $k => $val){
            $search_uids.=$val['fromuid'].',';
        }
        $search_uids = rtrim($search_uids,',');
        $sql = " select  uid,username,mobile from ".tablename(t_fans)." where themeid='$themeid' and uid in (".$search_uids.") ";
        $list = db_select($sql);
        return $list;
    }

    //手机端管理后台
    public static function adminOtherform($system=[],$theme=[],$config=[],$myworker=[])
    {
        global $_P, $_G,$_S;
        $themeid = intval($_P['themeid']);
        $search = isset($_P['searchtxt'])?$_P['searchtxt']:"";
        $workerid = isset($_P['select_workerid'])?$_P['select_workerid']:0;
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $op = isset($_P['op'])?$_P['op']:'display';

        $show_help_flag = 0;
        //盲盒判断
        if ($config['get_mystery_boxes']>0){
            if (!Common::get_open_other_form($system,$config)){
                $show_help_flag = 1;
            }
        }
        //点亮星星判断
        if ($config['isicon']==3 && $config['iconziliao']!=1){
            $show_help_flag = 1;
        }

        $condition = "";
        if ($search) {
            $search1 = "%".$search."%";
            if ($show_help_flag==1){
                $condition .= " AND (b.nickname LIKE '" . $search1 . "'" . " or b.username LIKE '" . $search1 . "' " . " or b.mobile LIKE '" . $search1 . "') ";
            }else{
                $condition .= " AND (b.nickname LIKE '" . $search1 . "'" . " or b.username LIKE '" . $search1 . "' " . " or b.mobile LIKE '" . $search1 . "' " . " or a.fileds LIKE '" . $search1 . "') ";
            }

        }
        if (isset($_P['uids']) && $_P['uids']){
            $condition .= " and a.uid in (".$_P['uids'].") ";
        }
//        if (isset($_P['fromuid']) && $_P['fromuid']){
//            $fromuid = $_P['fromuid'];
//            $condition .= " and a.fromuid='$fromuid' ";
//        }
        if ($workerid || $myworker['level']==3){
            if ($myworker['level']==3){
                $workerid = $myworker['uid'];
            }
            $condition .= " and a.workerid='$workerid' ";
        }

        if ($show_help_flag==1){
            $condition .= " ORDER BY a.addtime DESC ";
        }else{
            $condition .= " ORDER BY a.created_at DESC ";
        }


        if ($show_help_flag==1){
            $sql_prefix =  tablename(t_friend) ;
        }else{
            $sql_prefix =  tablename(t_fans_other_form) ;
        }
        $sql = " SELECT count(*) as cnt FROM " . $sql_prefix . " AS  a " .
            " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
            " LEFT JOIN " . tablename(t_fans) . " AS c on a.fromuid=c.uid and a.themeid = c.themeid" .
            " WHERE a.themeid=$themeid" . $condition;
        $total =  db_find($sql)['cnt'];
        
        $has_flag_total = 0;

        $last_sql = "";
        if ($workerid){
            $last_sql = " and a.workerid='$workerid' ";
        }
//        已追踪
        $sql1 = " SELECT count(*) as cnt FROM " . $sql_prefix . " AS  a " .
            " LEFT JOIN " . tablename(t_userdata_all) . " AS c on a.uid=c.uid and a.themeid = c.themeid" .
            " WHERE a.themeid=$themeid and c.sign_type>0 ".$last_sql;
        $has_flag_total =  db_find($sql1)['cnt'];

//        未追踪
        $no_flag_total = 0;
        $sql2 = " SELECT count(*) as cnt FROM " . $sql_prefix . " AS  a " .
            " LEFT JOIN " . tablename(t_userdata_all) . " AS c on a.uid=c.uid and a.themeid = c.themeid" .
            " WHERE a.themeid=$themeid and c.sign_type=0 ".$last_sql;
        $no_flag_total =  db_find($sql2)['cnt'];

        if ($page_size) {
            $condition .= "LIMIT " . $page_start . "," . $page_size;
        }
        $hasNext = true;
        $max_page = ceil($total/$page_size);
        if ($op=='has_flag'){
            $max_page = ceil($has_flag_total/$page_size);
        }elseif ($op=='no_flag'){
            $max_page = ceil($no_flag_total/$page_size);
        }

        if ($page_index>=$max_page){
            $hasNext = false;
        }
        if ($op=='display'){
            $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile,b.workerid as f_workerid,c.uid as fuid,c.avatar as favatar,c.nickname as fnickname FROM " . $sql_prefix . " AS  a " .
                " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
                " LEFT JOIN " . tablename(t_fans) . " AS c on a.fromuid=c.uid and a.themeid = c.themeid" .
                " WHERE a.themeid=$themeid" . $condition;
            $list =  db_select($sql);
        }elseif ($op=='has_flag'){
            $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile,b.workerid as f_workerid,c.uid as fuid,c.avatar as favatar,c.nickname as fnickname FROM " . $sql_prefix . " AS  a " .
                " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
                " LEFT JOIN " . tablename(t_fans) . " AS c on a.fromuid=c.uid and a.themeid = c.themeid" .
                " LEFT JOIN " . tablename(t_userdata_all) . " AS d on a.uid=d.uid and a.themeid = d.themeid" .
                " WHERE a.themeid=$themeid  and d.sign_type>0 " . $condition;
            $list =  db_select($sql);
        }elseif ($op=='no_flag'){
            $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile,b.workerid as f_workerid,c.uid as fuid,c.avatar as favatar,c.nickname as fnickname FROM " . $sql_prefix . " AS  a " .
                " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
                " LEFT JOIN " . tablename(t_fans) . " AS c on a.fromuid=c.uid and a.themeid = c.themeid" .
                " LEFT JOIN " . tablename(t_userdata_all) . " AS d on a.uid=d.uid and a.themeid = d.themeid" .
                " WHERE a.themeid=$themeid  and d.sign_type=0 " . $condition;

            $list =  db_select($sql);
        }
        if (!$show_help_flag){
            $format_fileds_arr = self::formatConfig($themeid,2);
        }
        foreach($list as $k => $val){
            $tmp_all_arr = [];
            if (!$show_help_flag){
                $temp_fileds = json_decode($val['fileds'],true);
                foreach ($format_fileds_arr as $k1 => $v1){
                    foreach ($temp_fileds as $kk => $vv){
                        $list[$k][$kk] = $vv;
                        if ($v1['key']==$kk){
                            $tmp_str = $v1['name'].':'.$vv;
                            array_push($tmp_all_arr,$tmp_str);
                        }
                    }
                }
            }

            if ($val['fnickname']){
                $tmp_str = '上级：'.$val['fnickname'];
                array_push($tmp_all_arr,$tmp_str);
            }
            if ($_S['ruanjian']==10){
                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/weike/core/model.php');
                $wk_info = \WeikeModel::getWkInfoByOtherformUid($themeid,$val['uid']);
                if ($wk_info && $wk_info['name']){
                    $tmp_str = '客片名称：'.$wk_info['name'];
                    array_push($tmp_all_arr,$tmp_str);
                }
            }
            $list[$k]['moreinfo'] = $tmp_all_arr;
            $list[$k]['isshow'] = false;
            if (!$show_help_flag){
                foreach ($temp_fileds as $kk => $vv){
                    $list[$k][$kk] = $vv;
                }
            }

            if (isset($val['workerid']) && $val['workerid']){
                $workerid = $val['workerid'];
            }else{
                $workerid = $val['f_workerid'];
            }
            if ($workerid){
                $r = Worker::getWokerName($_S,$themeid,$workerid);
                $list[$k]['workername'] = $r['teamname'].'-'.$r['workername'];
            }else{
                $list[$k]['workername'] = '无员工';
            }

            $themyrecord = Record::getLastGroupByUid($val['uid'],$themeid);
            if (!$themyrecord){
                $list[$k]['order_info']='未支付';
            }else{
                if ($themyrecord['status']==1){
                    $list[$k]['order_info']='已支付';
                }elseif ($themyrecord['status']==0){
                    $list[$k]['order_info']='未支付';
                }
            }
            unset($list[$k]['fileds']);
        }
        return ['hasNext'=>$hasNext,'list'=>$list,'page'=>$page_index,'total'=>$total,'has_flag_total'=>$has_flag_total,'no_flag_total'=>$no_flag_total];
    }

    public static function getSJWorkerList($themeid,$sjid)
    {
        $sql = " select uid,username from ".tablename(t_worker)." where themeid=$themeid and company=$sjid";
        return db_select($sql);
    }

    /**
     * Desc:获取开启状态以及信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/4/18 09:58
     * @param $system
     * @param $themeid
     * @return array
     */
    public static function getBaseInfoAndInput($system,$theme,$config,$fans)
    {
        $open_other_form = false;
        $return_info = [];
        if (Common::get_open_other_form($system,$config)){
            $open_other_form = true;
            $return_info = self::formatConfig($theme['id'],3);
        }

        $fansinfo = db_find('SELECT * FROM ' . tablename(t_record) . "
                        WHERE username <> '' and mobile <> '' and uid = :uid" , array(':uid' => $fans['uid']));
        if (!empty($fansinfo)){
            foreach ($return_info as $k =>$v){
                if ($v['mode']==8) {
                    $return_info[$k]['input_value'] = $fansinfo['username'];
                }elseif ($v['mode']==6) {
                    $return_info[$k]['input_value'] = $fansinfo['mobile'];
                }
            }
        }

        //查询用户是否有输入信息
        $fans_form_info = self::getItem(['themeid'=>$theme['id'],'uid'=>$fans['uid']]);
        if ($fans_form_info){
            $fileds = json_decode($fans_form_info['fileds'],true);
            foreach ($return_info as $k =>$v){
                if ($v['mode']==4){
                    $return_info[$k]['input_value'] = explode("|",$fileds[$v['input_name']]);
                }elseif ($v['mode']==5){
                    $return_info[$k]['input_value'] = explode("|",$fileds[$v['input_name']]);
                } else{
                    $return_info[$k]['input_value'] = $fileds[$v['input_name']];
                }
            }
        }
        return ['status'=>$open_other_form,'info'=>$return_info];
    }
}